#include "pch.h"
#include <stdio.h>

#pragma pack(1)
typedef struct 
{
	BYTE type; //OP code, 0xE9 for JMP
	DWORD address;
} patch_t;
#pragma pack()

BOOL applyPatch(BYTE type, DWORD address, const void *target, BYTE *replaced, DWORD *replacedSize) {
	DWORD dwOldValue, dwTemp;
	patch_t pWrite = {
		type,
		(DWORD)target - (address + sizeof(DWORD) + sizeof(BYTE))
	};

	VirtualProtect((LPVOID)address, sizeof(DWORD), PAGE_EXECUTE_READWRITE, &dwOldValue);
	ReadProcessMemory(GetCurrentProcess(), (LPVOID)address, (LPVOID)replaced, sizeof(pWrite), (PDWORD)replacedSize); //Keep track of the bytes we replaced
	BOOL bSuccess = WriteProcessMemory(GetCurrentProcess(), (LPVOID)address, &pWrite, sizeof(pWrite), NULL);
	VirtualProtect((LPVOID)address, sizeof(DWORD), dwOldValue, &dwTemp);

	return bSuccess;
}

void formatBytesArrayToString(const char *buf, int len, PTCHAR target) {
	int offset = 0, len1 = 3, len2 = 4;
	const TCHAR fmt1[] = TEXT("%02X ");
	const TCHAR fmt2[] = TEXT("%02X\r\n");
	int bufCnt1 = wcslen(fmt1) + 2, bufCnt2 = wcslen(fmt2) + 2;
	for (int i = 0; i < len; i++) {
		if (i % 16 == 15) {
			swprintf_s(&target[offset], bufCnt2, fmt2, (BYTE)buf[i]);
			offset += len2;
		} else {
			swprintf_s(&target[offset], bufCnt1, fmt1, (BYTE)buf[i]);
			offset += len1;
		}
	}
}
